package com.imachen.user.service.impl;

import com.imachen.basic.exception.BusinessException;
import com.imachen.basic.service.impl.BaseServiceImpl;
import com.imachen.basic.utils.Md5Utils;
import com.imachen.basic.utils.StrUtils;
import com.imachen.user.domain.Logininfo;
import com.imachen.user.domain.User;
import com.imachen.user.dto.UserDto;
import com.imachen.user.mapper.LogininfoMapper;
import com.imachen.user.mapper.UserMapper;
import com.imachen.user.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public void phoneRegister(UserDto userDto) {
        String phone = userDto.getPhone();
        String phoneCode = userDto.getPhoneCode();
        String pwd = userDto.getPwd();
        String rePwd = userDto.getRePwd();
        //一：校验：空值校验
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(phoneCode)
                ||StringUtils.isEmpty(pwd) ||StringUtils.isEmpty(rePwd) ){
            throw new BusinessException("信息不能为空！");
        }
        //二：校验：密码是否相同
        if (!pwd.equals(rePwd)){
            throw new BusinessException("两次输入的密码不一致");
        }
        //三：校验：短信验证码是否过期或是否正确
        Object codeObj = redisTemplate.opsForValue().get("register:" + phone);
        if (codeObj==null){
            throw new BusinessException("手机验证码已过期，请从新获取");
        }
        if (!codeObj.toString().split(":")[0].equals(phoneCode)){
            throw new BusinessException("手机验证码输入错误");
        }
        //四：添加到数据库
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        //1.先添加t_logininfo 获取自增id
        logininfoMapper.add(logininfo);
        //2.再添加t_user
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
    }

    @Override
    public void emailRegister(UserDto userDto) throws MessagingException {
        String email = userDto.getEmail();
        String emailCode = userDto.getEmailCode();
        String pwd = userDto.getPwd();
        String rePwd = userDto.getRePwd();
        //一：校验：空值校验
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(pwd)
                || StringUtils.isEmpty(rePwd) || StringUtils.isEmpty(emailCode) ){
            throw new BusinessException("信息不能为空");
        }
        //二：校验：密码是否相同
        if (!pwd.equals(rePwd)){
            throw new BusinessException("两次输入的密码不一致");
        }
        //三：校验：短信验证码是否过期或是否正确
        Object codeObj = redisTemplate.opsForValue().get("register:" + email);
        if (codeObj==null){
            throw new BusinessException("手机验证码已过期，请从新获取");
        }
        if (!codeObj.toString().split(":")[0].equals(emailCode)){
            throw new BusinessException("手机验证码输入错误");
        }
        //四：添加到数据库
        User user = userDto2Email(userDto);
        Logininfo logininfo = user2Logininfo(user);
        //1.先添加t_logininfo 获取自增id
        logininfoMapper.add(logininfo);
        //2.再添加t_user
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);


    }

    private User userDto2Email(UserDto userDto) {
        User user = new User();
        user.setUsername(userDto.getEmail());
        user.setEmail(userDto.getEmail());
        // 生成随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 密码加密加盐
        String md5Pwd = Md5Utils.encrypByMd5(userDto.getPwd() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }

    private User userDto2User(UserDto userDto) {
        User user = new User();
        user.setUsername(userDto.getPhone());
        user.setPhone(userDto.getPhone());
        // 生成随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 密码加密加盐
        String md5Pwd = Md5Utils.encrypByMd5(userDto.getPwd() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }


    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //按照属性同名原则
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);//用户
        logininfo.setDisable(true);
        return logininfo;
    }

    @Override
    @Transactional
    public void add(User user) {
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        //保存logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        logininfoMapper.add(logininfo);

        //保存user
        user.setLogininfoId(logininfo.getId());
        super.add(user);
    }


    @Override
    @Transactional
    public void delete(Long id) {
        //删除登录信息logininfo
        User user = userMapper.findOneById(id);
        logininfoMapper.delete(user.getLogininfoId());

        //删除user信息
        userMapper.delete(id);
    }

    @Override
    @Transactional
    public void update(User user) {//网上传递的user时没有loggininfo_id
        //处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        super.update(user);

        //获取登录信息id
        Long logininfoId = userMapper.findOneById(user.getId()).getLogininfoId();

        //创建logininfo
        Logininfo logininfo = logininfoMapper.findOneById(logininfoId);//id,type ,state
        //将新的数据覆盖旧的数据
        BeanUtils.copyProperties(user,logininfo);//5个数据新的 - 用户名，邮箱，电话，盐值，密码
        logininfoMapper.update(logininfo);
    }

}
